package cn.com.callback
import groovy.json.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import groovy.swing.impl.DefaultAction;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import cn.com.kh.CheckPhoneNo;

import cn.com.elite.Util;


public class syncIVRNotifiyCall implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(syncIVRNotifiyCall.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");
		log.debug("start syncIVRNotifiyCall-----------------");
		log.debug("request--:" + request);

		String getMethod = request.getMethod();
		String callJson = "";
		BufferedReader iny = null;

		def OUTArray = "";
		def reJson = "";

		log.debug("getMethod:" + getMethod);
		if (getMethod.equals("GET")) {
			callJson = request.getParameter("data");
			log.debug("原始Get请求参数:" + callJson);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				callJson += line;
			}
			log.debug("原始Post请求参数:" + callJson);
		}


		try {
			//解析返回Json内容
			JSONObject jsonObject = new JSONObject(callJson);

			//解析所需要的值
			String source = GetJV(jsonObject, "source");
			String submittime = GetJV(jsonObject, "submittime");
			String reData = GetJV(jsonObject, "data");
			String reCallPolicy = GetJV(jsonObject, "callpolicy");
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
			String Batch_No = source + "_" + simpleDateFormat.format(new Date()).toString();

			log.debug("调用reData：" + reData);
			log.debug("调用reCallpolicy：" + reCallPolicy);

			JSONArray dataArray = new JSONArray(reData);
			JSONArray callPolicyArray = new JSONArray(reCallPolicy);

			int dataArrayLen = dataArray.length();
			int callPolicyArrayLen = callPolicyArray.length();

			log.debug("调用DataArray：" + dataArray.toString() + "DataArray Size:" + dataArrayLen);
			log.debug("调用DataArray：" + callPolicyArray.toString() + "DataArray Size:" + callPolicyArrayLen);

			if(dataArrayLen>0 && callPolicyArrayLen>0) {

				//处理主数据
				JSONObject dataObject = null;
				for(int i = 0; i < dataArrayLen; i++) {
					dataObject = dataArray.getJSONObject(i);

					String  Rec_Guid = UUID.randomUUID().toString();

					def ncid = GetJV(dataObject, "ncid");
					def callno = GetJV(dataObject, "callno");
					def content = GetJV(dataObject, "content");
					def priority = GetJV(dataObject, "priority");

					def updateSQL="Update IVR_CallNotice Set Status = '-1' Where Status = '0' And Ncid = '" + ncid + "'";
					log.debug("将重复任务更新为失败SQL:" + updateSQL);
					eliteBean.update(updateSQL, 'dataSource');

					def insertSQL="Insert Into Ivr_Callnotice (Rec_Guid, Source, Batch_No, Ncid, Callno, Content, Priority, Submittime, Sync_Time, Status) Values ('" + Rec_Guid + "', '" + source + "', '" + Batch_No + "', '" + ncid + "', '" + callno + "', '" + content + "', '" + priority + "', '" + submittime + "', getdate(), '0')";
					log.debug("将任务插入外呼待处理表SQL:"+insertSQL);
					eliteBean.update(insertSQL,'dataSource');

					//外呼号码及外呼播报内容检查
					String checkResult = null;
					boolean initCheck = CheckPhoneNo.check(callno);
					if(initCheck) {
						if(content==null||content.length()<=0) {
							checkResult = "9002";
						}

					}else {
						checkResult = "9001";
					}

					//处理主数据
					JSONObject callPolicyObject = null;
					for(int j = 0; j < callPolicyArrayLen; j++) {
						callPolicyObject = callPolicyArray.getJSONObject(j);

						def calltime = GetJV(callPolicyObject, "calltime");

						def insertSQL2 = "";

						if(checkResult != null && checkResult.length() > 0) {
							insertSQL2 = "Insert Into Ivr_Callnotice_Policy (Policy_Guid, Rec_Guid, Calltime, CallResult) Values (NewID(), '" + Rec_Guid + "', Dateadd(Ms, Cast((Rand() * 1000 + 1) As Int), Convert(Datetime, '" + calltime + "')), '" + checkResult + "')";

						}else {
							insertSQL2 = "Insert Into Ivr_Callnotice_Policy (Policy_Guid, Rec_Guid, Calltime) Values (NewID(), '" + Rec_Guid + "', Dateadd(Ms, Cast((Rand() * 1000 + 1) As Int), Convert(Datetime, '" + calltime + "')))";
						}

						log.debug("将外呼策略插入外呼策略表SQL:" + insertSQL2);
						eliteBean.update(insertSQL2, 'dataSource');

					}

				}

				//调用存储过程处理工单
				log.debug("调用存储过程处理SQL...");
				def procedure="{call Dbo.Job_DealCallNotice(?,?,?)}";
				def inputMap = new String[2];
				inputMap[0] = Batch_No;
				inputMap[1] = "IN";

				log.debug("调用存储过程处理SQL:" + procedure);
				def reSult = eliteBean.executeWithReturn(procedure, inputMap, 'dataSource');
				log.debug("调用存储过程处理返回:" + reSult);

			}
			else {

				reJson= "{\"code\":\"0\",\"message\":\"外呼任务数据或外呼拨打策略异常!失败Desc:" + dataArrayLen + "/"+ callPolicyArrayLen + "\"}";
			}

			reJson= "{\"code\":\"1\",\"message\":\"处理完成!\"}";

		}
		catch(Exception e) {
			log.debug("接口处理异常" + e.getMessage());
			//失败返回
			reJson= "{\"code\":\"0\",\"message\":\"处理失败!失败Desc:" + e.getMessage() + "\"}";

		}

		log.debug("syncIVRNotifiyCall返回Json:" + reJson);
		return reJson;
	}

	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				log.warn("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = "";
			}else {
				log.debug("GetJV 获取参数值-" + getKey + ":" + Rev_Value);
			}
		}
		return Rev_Value;
	}
}